package com.spark.mock.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;


@Slf4j
public class HttpUtil extends cn.hutool.http.HttpUtil {


	/**
	 *  用于提交登录数据
	 */
	private HttpPost httpPost;


	public static final String CONTENT_TYPE = "Content-Type";





	/**
	 * @Title  发送请求post
	 */
	public String postUTF8(String url,String data) throws IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader(CONTENT_TYPE, "application/json");
		log.info("请求数据为:" + data);
		log.info("请求数据为:" + new StringEntity(data, "UTF-8"));
		httpPost.setEntity(new StringEntity(data, "UTF-8"));
		CloseableHttpResponse response = httpclient.execute(httpPost);
		String resp;
		try {
			// image/jpeg
			// application/json; encoding=utf-8
			HttpEntity entity = response.getEntity();
			Header contentType = entity.getContentType();
			if(contentType.getValue().contains("image")){ // 返回的时二维码的长度
				byte[] bytes = EntityUtils.toByteArray(entity);
				resp = new String(Base64.encodeBase64(bytes));
			}else{
				resp = EntityUtils.toString(entity);
			}
			EntityUtils.consume(entity);
		} finally {
			response.close();
		}
		return resp;
	}

	//2-InputStream转化为base64
	public static String getBase64FromInputStream(InputStream in) {
		// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		byte[] data = null;
		// 读取图片字节数组
		try {
			ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
			byte[] buff = new byte[100];
			int rc = 0;
			while ((rc = in.read(buff, 0, 100)) > 0) {
				swapStream.write(buff, 0, rc);
			}
			data = swapStream.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		String str = new String(Base64.encodeBase64(data));
		System.out.println("str length: " + str.length() + "  str: " + str);
		return str;
	}




}
